package com.tledu.interceptor;

import com.tledu.model.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        String methodName = handlerMethod.getMethod().getName();
        System.out.println("访问的方法名="+methodName);
        //true表示能从request中获取到session就session，获取不到就创建一个session
        HttpSession session = request.getSession(true);
        User loginUser = (User) session.getAttribute("loginUser");
        if(loginUser == null){
            response.sendRedirect(request.getContextPath()+"/");
            //返回false表示拦截这个请求不能通行
            return false;
        }
        //放行
        return super.preHandle(request, response, handler);
    }
}
